from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import urlfetch

import utils
import logging
import urllib
import yaml
import settings
import cgi
import urllib
import json
import random
import string

class SingletonUsercounter(db.Model):
    channel_id    = db.StringProperty()
    event_key     = db.StringProperty()
    destroy_key   = db.StringProperty()
    counter       = db.IntegerProperty()

def get_singleton():
    s = SingletonUsercounter.all().fetch(1)
    if len(s) < 1:
        s = SingletonUsercounter()
        s.counter = 0
        s.channel_id = 'notset'
        s.save()
        s = SingletonUsercounter.all().fetch(1)
        assert s
    s = s[0]
    return s

def send_event(channel_id, msg, event_key):
    q = urllib.urlencode({
        'data':      msg,
        'event_key': event_key,
    })
    resp = urlfetch.fetch('http://comet.%s/comet/%s/event' % (settings.SERVICESURL, channel_id), payload=q, method=urlfetch.POST, headers={}, allow_truncated=False)
    if resp.status_code != 200:
        logging.error("sending event failed to ch %s" % channel_id)
    return

class Main(webapp.RequestHandler):
    def get(self):
        s = get_singleton()
        counter = [0]
        def set_channel_id(key, amount):
            obj = db.get(key)
            if not obj.counter:
                obj.counter = 0
            obj.counter += 1
            counter[0] = obj.counter
            obj.put()
        db.run_in_transaction(set_channel_id, s.key(), 5)
        
        send_event(s.channel_id, "%s" % counter[0], s.event_key)
        
        self.response.out.write(utils.render_to_mako('usercounter/usercounter_main.html',
            {'servicesurl':settings.SERVICESURL, 
            'domain':settings.TOPDOMAIN,}))

class ChannelUri(webapp.RequestHandler):
    def get(self):
        s = get_singleton()
        try:
            resp = urlfetch.fetch('http://comet.%s/comet/%s/?rand=%f' % (settings.SERVICESURL, s.channel_id, random.random() ), method=urlfetch.GET, headers={}, allow_truncated=True)
        except urlfetch.DownloadError:
            resp = None
        if resp and resp.status_code != 200:
            q = urllib.urlencode({
                'public':      'False',
            })
            
            resp = urlfetch.fetch('http://comet.%s/comet/create_channel' % (settings.SERVICESURL), payload=q, method=urlfetch.POST, headers={}, allow_truncated=True)
            if resp.status_code != 200:
                logging.error("creating channel failed %.250r!" % (q, resp.content) )
                return
            
            dd = yaml.load(resp.content)
            
            def set_channel_id(key, amount):
                obj = db.get(key)
                # noone haven't modified the record?
                if s.channel_id == obj.channel_id:
                    obj.channel_id = dd['channel_id']
                    obj.event_key  = dd['event_key']
                    obj.destroy_key= dd['destroy_key']
                obj.put()
            db.run_in_transaction(set_channel_id, s.key(), 5)
            s = db.get(s.key())
        
        o = {
            'channel_id': s.channel_id,
            'counter':    s.counter,
        }
        self.response.out.write(json.write(o))
